package com.stockz.core.dao.hsql;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.stockz.core.dao.BarDao;
import com.stockz.core.model.Bar;

@Repository
@Transactional
public class BarDaoImpl implements BarDao {
	
	private EntityManager entityManager;
	
	@PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
	
	@Transactional(propagation=Propagation.MANDATORY)
	public void persist(Bar bar){
		if(bar != null && bar.getCode() != null
				&& 0 != bar.getCode().trim().length() && bar.getDate() != null){
			entityManager.persist(bar);
			entityManager.flush();
		}
	}
	
	@Transactional(propagation=Propagation.MANDATORY)
	public <T extends Collection<? extends Bar>> void persistAll(T barCollection) {
		if(barCollection != null && !barCollection.isEmpty()){
			for(Bar bar : barCollection){
				if(bar != null && bar.getCode() != null
						&& 0 != bar.getCode().trim().length() && bar.getDate() != null){
					entityManager.persist(bar);
				}
			}
			entityManager.flush();
		}
	}
	
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public Date getMaxBarDate() {
		return (Date)entityManager.createQuery("select max(date) from Bar").getSingleResult();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Bar> getBarList(String code) {
		if(StringUtils.hasText(code)){
			Query query = entityManager.createNamedQuery(Bar.getBarListByCodeQuery);
			query.setParameter("code", code);
			return query.getResultList();
		}
		return Collections.emptyList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Bar> getBarList(String code, int maxCount) {
		if(StringUtils.hasText(code)){
			Query query = entityManager.createNamedQuery(Bar.getBarListByCodeQuery);
			query.setParameter("code", code);
			query.setMaxResults(maxCount);
			return query.getResultList();
		}
		return Collections.emptyList();
	}
	
}
